package driver.android;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import driver.android.adapter.UserInfoListAdapter;
import driver.android.http.CommonOkHttpClient;
import driver.util.Constants;
import driver.util.IHttpCallBack;
import driver.util.Util;
import okhttp3.Response;

public class FlashDriverUserInfoActivity extends Activity implements View.OnClickListener, IHttpCallBack {

    private Button mLogoutButton;
    private String mToken;
    private String mUuid;
    private String mFlashSharePreferenceName = "Flash";
    private SharedPreferences mFlashSharedPreferences;
    private FlashDriverTaskHandler mHandler;
    private ProgressDialog mProgressDialog;
    private Button mBack;
    private ListView mUserInfoList;
    private UserInfoListAdapter mUserInfoListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.f_user_info_activity);
        mLogoutButton = (Button) this.findViewById(R.id.logout_button);
        mLogoutButton.setOnClickListener(this);
        mBack = (Button) this.findViewById(R.id.back_package_list_button);
        mBack.setOnClickListener(this);
        mUserInfoList = this.findViewById(R.id.user_info_list);
        mProgressDialog = new ProgressDialog(this);
        mHandler = new FlashDriverTaskHandler(this);
        mFlashSharedPreferences = getSharedPreferences(mFlashSharePreferenceName, Context.MODE_PRIVATE);
        mToken = mFlashSharedPreferences.getString("token", "");
        mUuid = mFlashSharedPreferences.getString("uuid", "");
        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            String userInfo = bundle.getString("userInfo");
            if (userInfo != null && userInfo.length() > 0) {
                mUserInfoListAdapter = new UserInfoListAdapter(this, R.layout.f_user_info_item, userInfo);
                mUserInfoList.setAdapter(mUserInfoListAdapter);
            }
        }
    }

    //    获取app版本信息
    private String getAppNameInfo() {
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            String versionName = this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "1.0.0";
    }

    private void showToast(String title) {
        Toast.makeText(this, title, Toast.LENGTH_LONG).show();
    }

    private void logout() {
        if (mToken != null) {
            CommonOkHttpClient okHttpInstance = CommonOkHttpClient.getInstance(this);
            Map<String, String> headersParams = new HashMap<>();
            headersParams.put("token", mToken);
            String url = Constants.ROOT + mUuid + Constants.LOG_OUT;
            Util.debugApp('d', "登出的url " + url);
            okHttpInstance.doPut(url, headersParams, null);
        }
    }

    private void showProgressDialog(String title) {
        if (mProgressDialog != null) {
            mProgressDialog.setMessage(title);
            mProgressDialog.setCanceledOnTouchOutside(false);
            if (!this.isFinishing()) {
                mProgressDialog.show();
            }
        }
    }

    private void closeProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void parseJsonBundle(Bundle bundle) {
        String taskJsonDetail = bundle.getString("taskBody");
        if (taskJsonDetail != null && taskJsonDetail.equals("true")) {
            SharedPreferences.Editor editor = mFlashSharedPreferences.edit();
            editor.putString("token", "");
            editor.putString("uuid", "");
            editor.commit();
            Intent intent = new Intent();
            intent.setClass(this, FlashDriverLoginActivity.class);
            this.startActivity(intent);
            this.finish();
        } else if (taskJsonDetail != null && taskJsonDetail.equals("false")) {
            showToast("Network Error...");
        }
    }

    private static class FlashDriverTaskHandler extends Handler {

        private final WeakReference<FlashDriverUserInfoActivity> mActivity;

        private FlashDriverTaskHandler(FlashDriverUserInfoActivity ac) {
            this.mActivity = new WeakReference<FlashDriverUserInfoActivity>(ac);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FlashDriverUserInfoActivity activity = mActivity.get();
            if (activity != null) {
                activity.closeProgressDialog();
                switch (msg.what) {
                    case Constants.LOG_OUT_SUCCESS_MESSAGE:
                        Util.debugApp('d', "获取远端信息成功的消息");
                        Bundle bundle = msg.getData();
                        activity.parseJsonBundle(bundle);
                        break;
                    case Constants.LOG_OUT_FAIL_MESSAGE:
                        Util.debugApp('d', "获取远端信息失败的消息");
                        activity.showToast("Network Error...");
                        break;
                    case Constants.UN_KNOW_RESPONSE_CODE:
                        Bundle bundleUnKnowCode = msg.getData();
                        String unKnowBody = bundleUnKnowCode.getString("codeInvalid");
                        String description = Util.getJsonKeyValue("description", unKnowBody);
                        if (description == null) {
                            activity.showToast("Logout Error");
                        } else {
                            activity.showToast(description);
                        }
                        break;
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        boolean connect = Util.isNetworkAvailable(this);
        if (!connect) {
            showToast("Please check your network state");
            return;
        }
        int id = v.getId();
        switch (id) {
            case R.id.logout_button:
                showProgressDialog("Please wait...");
                logout();
                break;
            case R.id.back_package_list_button:
                Intent intent = new Intent();
                intent.setClass(this, FlashDriverPackageListActivity.class);
                this.startActivity(intent);
                this.finish();
                break;
        }
    }

    @Override
    public void success(Response response) {
        Message logoutSuccessMessage = mHandler.obtainMessage();
        Bundle bundle = new Bundle();
        try {
            String body = response.body().string();
            logoutSuccessMessage.what = Constants.LOG_OUT_SUCCESS_MESSAGE;
            bundle.putString("taskBody", body);
            logoutSuccessMessage.setData(bundle);
            Util.debugApp('d', "获取远端信息成功body " + body);
        } catch (IOException e) {
            Util.debugApp('e', "获取远端信息成功但是转换失败" + e.toString());
            logoutSuccessMessage.what = Constants.LOG_OUT_FAIL_MESSAGE;
        }
        mHandler.sendMessage(logoutSuccessMessage);
    }

    @Override
    public void fail(IOException exception) {
        Message logoutFailMessage = mHandler.obtainMessage();
        logoutFailMessage.what = Constants.LOG_OUT_FAIL_MESSAGE;
        mHandler.sendMessage(logoutFailMessage);
        Util.debugApp('d', "logout失败" + exception.toString());
    }

    @Override
    public void codeInvalid(Response response) {
        Message unKnowMessage = mHandler.obtainMessage();
        unKnowMessage.what = Constants.UN_KNOW_RESPONSE_CODE;
        try {
            String body = response.body().string();
            Util.debugApp('d', "codeInvalid " + body);
            Bundle bundle = new Bundle();
            bundle.putString("codeInvalid", body);
            unKnowMessage.setData(bundle);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}